package ru.mipt.board.Analysis
import java.util.regex.{Matcher,Pattern};
/**
 * Created by IntelliJ IDEA.
 * User: IL
 * Date: 24.04.11
 * Time: 18:23
 * To change this template use File | Settings | File Templates.
 */

abstract  class Stemer{
  def Stem(word: String): String
}

/**
 * see http://www.algorithmist.ru/2010/12/porter-stemmer-russian.html
 **/
object  Porter extends Stemer{
  private val perfectground = Pattern.compile("((ив|ивши|ившись|ыв|ывши|ывшись)|((?<=[ая])(в|вши|вшись)))$")
  private val reflexive = Pattern.compile("(с[яь])$")
  private val adjective = Pattern.compile("(ее|ие|ые|ое|ими|ыми|ей|ий|ый|ой|ем|им|ым|ом|его|ого|ему|ому|их|ых|ую|юю|ая|яя|ою|ею)$")
  private val participle = Pattern.compile("((ивш|ывш|ующ)|((?<=[ая])(ем|нн|вш|ющ|щ)))$")
  private val verb = Pattern.compile("((ила|ыла|ена|ейте|уйте|ите|или|ыли|ей|уй|ил|ыл|им|ым|ен|ило|ыло|ено|ят|ует|уют|ит|ыт|ены|ить|ыть|ишь|ую|ю)|((?<=[ая])(ла|на|ете|йте|ли|й|л|ем|н|ло|но|ет|ют|ны|ть|ешь|нно)))$")
  private val noun = Pattern.compile("(а|ев|ов|ие|ье|е|иями|ями|ами|еи|ии|и|ией|ей|ой|ий|й|иям|ям|ием|ем|ам|ом|о|у|ах|иях|ях|ы|ь|ию|ью|ю|ия|ья|я)$")
  private val rvre = Pattern.compile("^(.*?[аеиоуыэюя])(.*)$")
  private val derivation = Pattern.compile(".*[^аеиоуыэюя]+[аеиоуыэюя].*ость?$")
  private val der = Pattern.compile("ость?$")
  private val superlative = Pattern.compile("(ейше|ейш)$")
  private val i = Pattern.compile("и$")
  private val p = Pattern.compile("ь$")
  private val nn = Pattern.compile("нн$")
  def Stem(word: String): String  = {
    var result = word.toLowerCase().replace('ё', 'е')
    val matcher = rvre.matcher(result)
    if(matcher.matches()){
      var pre = matcher.group(1)
      var rv = matcher.group(2)
      var temp = perfectground.matcher(rv).replaceFirst("");
        if (temp.equals(rv)) {
          rv = reflexive.matcher(rv).replaceFirst("");
                temp = adjective.matcher(rv).replaceFirst("");
                if (!temp.equals(rv)) {
                    rv = temp;
                    rv = participle.matcher(rv).replaceFirst("");
                } else {
                    temp = verb.matcher(rv).replaceFirst("");
                    if (temp.equals(rv)) {
                        rv = noun.matcher(rv).replaceFirst("");
                    } else {
                        rv = temp;
                    }
                }
            } else {
                rv = temp;
            }
            rv = i.matcher(rv).replaceFirst("");
            if (derivation.matcher(rv).matches()) {
                rv = der.matcher(rv).replaceFirst("");
            }
            temp = p.matcher(rv).replaceFirst("");
            if (temp.equals(rv)) {
                rv = superlative.matcher(rv).replaceFirst("");
                rv = nn.matcher(rv).replaceFirst("н");
            }else{
                rv = temp;
            }
      result = pre + rv
    }
    result
  }
}